const cookie = new Cookie();
var token = cookie.getCookie('token');
//初始化页面函数
$(function () {
  //获取用户登录状态
  getUserStatu();
  //获取购物车商品列表
  getCartList()
})

//获取用户登录状态
function getUserStatu() {
  if (!cookie.getCookie('uid')) {
    hsycms.tips('当前未登录，即将跳转到首页登陆', () => {
      setTimeout(() => {
        location.href = './index.html';
      }, 1500)
    })
    return
  } else {
    $('.username').text(cookie.getCookie('username'));
    $('.mycart').text(cookie.getCookie('username') + '的购物车');
  }
}
//获取购物车商品列表
function getCartList() {
  let token = cookie.getCookie('token');
  request({
    type: 'get',
    url: 'https://api.it120.cc/conner/shopping-cart/info',
    data: {
      token
    },
    loading: true,
    timeout: 3000
  }).then(res => {
    renderData(res)
  })

  /* $.ajax({
    type: 'get',
    url: 'https://api.it120.cc/conner/shopping-cart/info',
    data: {
      token
    }
  }).then(res => {
    renderData(res)
  }) */
}

//渲染购物车数据
function renderData(res) {
  if (res.code == 0) {
    const { number, price, items } = res.data;
    let str = '';
    //用于保存每一个商品的选择状态
    let selectArr = [];
    //根据flag的值判断初始化页面是否全选
    let flag = false;
    items.forEach(item => {
      str += `
              <tr class="warning">
                <td><input type="checkbox" ${item.selected ? 'checked' : ''} key="${item.key}"></td>
                <td>${item.name}</td>
                <td><img src="${item.pic}" alt="" class="img"></td>
                <td>${item.price}</td>
                <td><button class="btn btn-default desc-btn" key="${item.key}">-</button><span class="btn-local">${item.number}</span><button class="btn btn-default add-btn" key="${item.key}">+</button></td>
                <td class="price">${item.price * item.number}</td>
                <td><button class="btn btn-danger del-btn" key="${item.key}">删除</button></td>
              </tr>
            `
      $('.total-num').text(number);
      $('.total-price').text(price);
      //判断所有的商品勾选状态
      selectArr.push(item.selected)
      flag = selectArr.every(item => item)
    })
    $('tbody').html(str)
    //初始化全选按钮状态
    $('.check-all').prop('checked', flag)
  } else {
    // alert('网络请求出错')
    hsycms.tips('当前登录状态以过期，请重新登录', () => {
    }, 1500)
  }
}

//加商品数量
$('tbody').on('click', '.desc-btn', function () {
  let key = $(this).attr('key');
  let number = $(this).next().text();
  number--;
  request({
    type: 'post',
    url: 'https://api.it120.cc/conner/shopping-cart/modifyNumber',
    data: {
      key,
      number,
      token
    },
    loading: true,
    timeout: 3000
  }).then(res => {
    renderData(res)
  })

  /*   $.ajax({
      type: 'post',
      url: 'https://api.it120.cc/conner/shopping-cart/modifyNumber',
      data: {
        key,
        number,
        token
      }
    }).then(res => {
      renderData(res)
    }) */
})
//减商品数量
$('tbody').on('click', '.add-btn', function () {
  let key = $(this).attr('key')
  let number = $(this).prev().text();
  number++;
  request({
    type: 'post',
    url: 'https://api.it120.cc/conner/shopping-cart/modifyNumber',
    data: {
      key,
      number,
      token
    },
    loading: true,
    timeout: 3000
  }).then(res => {
    renderData(res)
  })
  /*  $.ajax({
     type: 'post',
     url: 'https://api.it120.cc/conner/shopping-cart/modifyNumber',
     data: {
       key,
       number,
       token
     }
   }).then(res => {
     renderData(res)
   }) */
})
//删除商品
$('tbody').on('click', '.del-btn', function () {
  let key = $(this).attr('key');
  hsycms.confirm('当前操作不可逆，请谨慎操作！',
    function () {
      hsycms.success('删除成功');
      setTimeout(function () {
        request({
          type: 'post',
          url: 'https://api.it120.cc/conner/shopping-cart/remove',
          data: {
            key,
            token
          },
          loading: true,
          timeout: 3000
        }).then(res => {
          renderData(res)
        })
      }, 1500)
    },
    function () {
      hsycms.fail('取消成功');
    },
  )
})

//勾选与取消勾选商品
$('tbody').on('click', 'input[type="checkbox"]', function () {
  let selected = $(this).prop('checked')
  let key = $(this).attr('key');
  request({
    type: 'post',
    url: 'https://api.it120.cc/conner//shopping-cart/select',
    data: {
      key,
      selected,
      token
    },
    loading: true,
    timeout: 3000
  }).then(res => {
    renderData(res)
  })
  /* $.ajax({
    type: 'post',
    url: 'https://api.it120.cc/conner//shopping-cart/select',
    data: {
      key,
      selected,
      token
    }
  }).then(res => {
    renderData(res)
  }) */
})

//全选与反选
$('.check-all').click(function () {
  let keyArr = [];
  let selected = $(this).prop('checked')
  $('input[type="checkbox"]').not('.check-all').each((index, item) => {
    keyArr.push($(item).attr('key'))
  })
  let key = keyArr.join(',');
  request({
    type: 'post',
    url: 'https://api.it120.cc/conner//shopping-cart/select',
    data: {
      key,
      selected,
      token
    },
    loading: true,
    timeout: 3000
  }).then(res => {
    renderData(res)
  })

  /*  $.ajax({
     type: 'post',
     url: 'https://api.it120.cc/conner//shopping-cart/select',
     data: {
       key,
       selected,
       token
     }
   }).then(res => {
     renderData(res)
   }) */
})

// 生成订单
$('.order-btn').click(function () {
  //获取订单数据
  /* 
    [{"goodsId":11,"number":2,"propertyChildIds":"","logisticsType":0, "days": ["2019-07-26", "2019-07-27"]}]
  */
  request({
    type: 'get',
    url: 'https://api.it120.cc/conner/shopping-cart/info',
    data: {
      token
    },
    timeout: 3000
  }).then(res => {
    let { items } = res.data;
    //将勾选的商品存入订单
    let goodsJsonStr = items.filter(item => item.selected);
    //后端接受json字符串
    goodsJsonStr = JSON.stringify(goodsJsonStr);
    //发送创建当但请求
    request({
      type: 'post',
      url: 'https://api.it120.cc/conner/order/create',
      data: {
        goodsJsonStr,
        token
      },
      loading: true,
      timeout: 3000
    }).then(res => {
      console.log(res);
      hsycms.confirm('创建订单成功，是否立刻去结算？',
        function () {
          hsycms.success('即将前往订单页');
          setTimeout(function () {
            location.href = './order.html'
            console.log(res);
          }, 1500)
        },
        function () {
          hsycms.fail('取消');
        },
      )
    })
  })
})


